import * as React from 'react';
import {
    Button,
    Image,
    Modal,
    Pressable,
    SafeAreaView,
    ScrollView,
    StyleSheet,
    Text,
    TextInput,
    ToastAndroid,
    TouchableHighlight,
    TouchableOpacity,
    View,
} from 'react-native';
import { DataTable, Dialog, List, Paragraph, Portal, Provider } from 'react-native-paper';
// import {
//     DOMAIN_URL,
//     deptInfoGet,
//     noticeUnread,
//     newsList,
//     eventList,
//     studyList,
//     newsRecent,
//     getCurrentUserInfo,
//     getTotalPointsPs,
//     getMouthPointsPs,
//     getTotalPointsRankPs,
//     getMouthPointsRankPs,
// } from '../../../util/api';
import { DOMAIN_URL, getUserInfoByLoginName, addUserInfo, getGroupList, getDeptList } from '../../../util/api';
import { style } from '../../../theme';
import { PAGENAME } from '../../../util/PageName';
import Icon from 'react-native-vector-icons/MaterialIcons';

class AddUserScreen extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            // userId: props?.route?.params?.userId,
            // user: {
            //     loginName: '',
            //     deptName: '研发部门',
            //     groupName: '测试党小组',
            //     userName: '管理员',
            //     isAdmin: '',
            // },
            user: {
                userId: "",
                loginName: "",
                userName: "",
                password: '',
                deptId: "",
                deptName: "",
                groupID: "",
                groupName: ""
            },
            groupList: [],
            deptList: [],
            modalVisibleDept: false,
            modalVisibleGroup: false,
        };
        // this.loadData()
    }

    componentDidMount() {
        this.subscription = this.props.navigation.addListener('focus', () => {
            // do something
            console.log('event detail');
            this.loadData()
        });
    }
    loadData = () => {
        console.log('load data');
        this.getGroupInfoList();
        this.getDeptInfoList();
    }

    componentWillUnmount() {
        this.subscription();
    }

    getGroupInfoList = () => {
        // 党小组
        getGroupList(null).then(res => {
            console.log('getGroupList', res);
            this.setState({
                groupList: res.rows
            })
        })

    };

    getDeptInfoList = () => {
        // 部门
        getDeptList(null).then(res => {
            console.log('getDeptList', res);
            this.setState({
                deptList: res.rows
            })
        })

    };


    saveEdit = () => {
        const user = this.state.user
        const groupList: any[] = this.state.groupList
        const deptList: any[] = this.state.deptList

        if (!deptList.find(v => v.deptName == user.deptName)) {
            user.deptId = null
        }
        if (!groupList.find(v => v.deptName == user.groupName)) {
            user.groupID = null
        }
        // 处理登录逻辑
        addUserInfo(user).then(res => {
            console.log(res);
            if (res.code == 0) {
                ToastAndroid.show('添加成功', 2000)
            } else {
                ToastAndroid.show(`添加失败：${res.msg}`, 2000)
            }
        })

    };
    private pickerRef: any;

    render() {
        const { navigation } = this.props;
        const { user, total, month, totalRank, monthRank } = this.state
        return (
            <SafeAreaView style={styles.container}>
                <ScrollView style={{ alignContent: 'center', paddingVertical: 20, paddingHorizontal: 8 }}>
                    <View style={{ marginTop: 16, marginBottom: 16, marginLeft: 8 }}>
                        <View style={styles.userRow}>
                            <Text style={styles.label}>登录名</Text>
                            <TextInput
                                style={style.inputArea}
                                value={user.loginName}
                                onChangeText={text => {
                                    user.loginName = text
                                    this.setState({
                                        user: user
                                    })
                                }}
                            />

                        </View>
                        <View style={styles.userRow}>
                            <Text style={styles.label}>姓名</Text>
                            <TextInput
                                style={style.inputArea}
                                value={user.userName}
                                onChangeText={text => {
                                    user.userName = text
                                    this.setState({
                                        user: user
                                    })
                                }}
                            />
                        </View>
                        <View style={styles.userRow}>
                            <Text style={styles.label}>部门</Text>
                            <View style={{ position: 'relative', }}>
                                <TextInput
                                    style={style.inputArea}
                                    value={user.deptName}
                                    onChangeText={text => {
                                        user.deptName = text
                                        this.setState({
                                            user: user
                                        })
                                    }}
                                />
                                {this.state.deptList.length > 0 && <TouchableOpacity
                                    style={{
                                        position: 'absolute',
                                        top: 8,
                                        right: 8,
                                        backgroundColor: 'rgba(0, 0, 0, 0.5)',
                                        width: 30,
                                        height: 30,
                                        justifyContent: 'center',
                                        alignItems: 'center',
                                    }}
                                    onPress={() => {
                                        console.log(123, this.pickerRef);
                                        // this.pickerRef.current.focus();
                                        this.setState({
                                            modalVisibleDept: true
                                        })
                                    }}>
                                    <Icon name={'expand-more'} size={18} color={'white'} />

                                </TouchableOpacity>}
                                <Modal
                                    // animationType="slide"
                                    transparent={true}
                                    // style={{ width: 100 ,}}
                                    visible={this.state.modalVisibleDept}
                                    onRequestClose={() => {
                                        this.setState({
                                            modalVisibleDept: !this.state.modalVisibleDept
                                        })
                                    }}
                                >
                                    <View style={styles.centeredView}>
                                        <View style={styles.modalView}>
                                            <List.Section>
                                                <List.Subheader>{'                 请选择                   '}</List.Subheader>
                                                {this.state.deptList.map((v, i) => {
                                                    return <List.Item title={v.deptName} onPress={() => {
                                                        const { user } = this.state
                                                        user.deptName = v.deptName
                                                        user.deptId = v.deptId
                                                        this.setState({ user: user })
                                                        this.setState({
                                                            modalVisibleDept: !this.state.modalVisibleDept
                                                        })
                                                    }} left={props => <List.Icon {...props} icon="circle-small" />} />
                                                })}
                                            </List.Section>
                                            <View>
                                                <Button title='取消' onPress={() => {
                                                    this.setState({
                                                        modalVisibleDept: !this.state.modalVisibleDept
                                                    })
                                                }} />
                                            </View>
                                        </View>
                                    </View>
                                </Modal>

                            </View>
                        </View>
                        <View style={styles.userRow}>
                            <Text style={styles.label}>小组</Text>
                            <View style={{ position: 'relative', }}>
                                <TextInput
                                    style={style.inputArea}
                                    value={user.groupName}
                                    onChangeText={text => {
                                        user.groupName = text
                                        this.setState({
                                            user: user
                                        })
                                    }}
                                />
                                {this.state.groupList.length > 0 && <TouchableOpacity
                                    style={{
                                        position: 'absolute',
                                        top: 8,
                                        right: 8,
                                        backgroundColor: 'rgba(0, 0, 0, 0.5)',
                                        width: 30,
                                        height: 30,
                                        justifyContent: 'center',
                                        alignItems: 'center',
                                    }}
                                    onPress={() => {
                                        console.log(123, this.pickerRef);
                                        // this.pickerRef.current.focus();
                                        this.setState({
                                            modalVisibleGroup: true
                                        })
                                    }}>
                                    <Icon name={'expand-more'} size={18} color={'white'} />

                                </TouchableOpacity>}
                                <Modal
                                    // animationType="slide"
                                    transparent={true}
                                    // style={{ width: 100 ,}}
                                    visible={this.state.modalVisibleGroup}
                                    onRequestClose={() => {
                                        this.setState({
                                            modalVisibleGroup: !this.state.modalVisibleGroup
                                        })
                                    }}
                                >
                                    <View style={styles.centeredView}>
                                        <View style={styles.modalView}>
                                            <List.Section>
                                                <List.Subheader>{'                 请选择                   '}</List.Subheader>
                                                {this.state.groupList.map((v, i) => {
                                                    return <List.Item title={v.deptName} onPress={() => {
                                                        const { user } = this.state
                                                        user.groupName = v.deptName
                                                        user.groupID = v.deptId
                                                        this.setState({
                                                            user: user,
                                                            modalVisibleGroup: !this.state.modalVisibleGroup
                                                        })
                                                    }} left={props => <List.Icon {...props} icon="circle-small" />} />
                                                })}
                                                {/* <List.Item title="Second Item" left={props => <List.Icon {...props} icon="circle-small" />} /> */}
                                            </List.Section>
                                            <View>
                                                <Button title='取消' onPress={() => {
                                                    this.setState({
                                                        modalVisibleGroup: !this.state.modalVisibleGroup
                                                    })
                                                }} />
                                            </View>

                                        </View>
                                    </View>
                                    {/* <View><Text>2222</Text></View> */}
                                </Modal>

                            </View>
                        </View>
                        <View style={styles.userRow}>
                            <Text style={styles.label}>密码</Text>
                            <TextInput
                                style={style.inputArea}
                                value={user.password}
                                secureTextEntry
                                onChangeText={text => {
                                    user.password = text
                                    this.setState({
                                        user: user
                                    })
                                }}
                            />
                        </View>
                    </View>
                    <View style={{ flexDirection: 'row', alignSelf: 'center', marginTop: 30 }}>
                        <View style={style.pageButton}>
                            <Button
                                title="保存"
                                onPress={() => {
                                    this.saveEdit()
                                    // navigation.push(PAGENAME.USER_EDIT, { userId: user.loginName });
                                }}
                            />
                        </View>
                    </View>
                </ScrollView>
            </SafeAreaView>
        );
        // </ImageBackground>
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        // paddingTop: StatusBar.currentHeight,
    },
    scoreTotal: {
        marginTop: 16,
        paddingVertical: 40,
        // marginLeft: 35
    },
    inputIcon: {
        ...style.inputArea,
    },
    label: {
        // width: 90,
        // marginLeft: 20,
        fontSize: 16,
        fontWeight: '600'
    },
    value: {
        marginLeft: 16,
        fontSize: 16,
        fontWeight: '600'
    },
    userRow: {
        // flexDirection: 'row',
        margin: 4
    },

    centeredView: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        marginTop: 22
    },
    modalView: {
        margin: 20,
        backgroundColor: "white",
        borderRadius: 4,
        padding: 35,
        alignItems: "center",
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5
    },
});

export default AddUserScreen;
